<template>
  <div class="box">
    <div class="box-header">{{ year }}年度账单</div>
    <div class="box-body" id="charts2"></div>
  </div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import { onMounted, computed, ref, reactive } from 'vue'
interface seriesObj {
  name: string,
  value: number
}
// 接受父组件数据
const prop = defineProps({
  data: { type: Array, default: [] },
})
const year =ref('2025')
const yearData = prop.data.filter((item)=>{
  return year.value === item.time.split('-')[0]
})
const option = computed(() => {
  return {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '',
        type: 'pie',
        data: series.value,
        label:{
          show:true,
          formatter: '{b}: {c}',
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
})
const myChartDom = ref(null)
const series = ref<any>([])
const dataFormatPie = (list, filed) => {
  // 分组
  const group = Object.groupBy(list, item => item[filed])
  const series: seriesObj[] = [];
  for (const key in group) {
    const seriesObj: seriesObj = { name: '', value: 0 }
    const sum = group[key].reduce((total, item) => total + parseFloat(item.price), 0);
    seriesObj.name = key
    seriesObj.value = Math.round(sum * 100) / 100; // 四舍五入保留2位小数
    series.push(seriesObj)
  }
  return series
}

onMounted(() => {
  myChartDom.value = echarts.init(document.getElementById('charts2'));
  series.value = dataFormatPie(yearData, 'leave1')
  myChartDom.value.setOption(option.value);
  
  myChartDom.value.on('click', function (params) {
    let list = yearData.filter(item=>item.leave1===params.data.name)
    if(list.length===0){
      series.value = dataFormatPie(yearData, 'leave1')
      myChartDom.value.setOption(option.value);
    }else{
      series.value = dataFormatPie(list, 'leave2')
      myChartDom.value.setOption(option.value);
    }
  });
})
</script>
<style scoped lang="scss">
.box {
  width: 100%;
  height: 100%;

  .box-header {
    width: 100%;
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    text-align: center;

  }

  .box-body {
    width: 100%;
    height: calc(100% - 50px);
    background: #fff;
  }
}
</style>
